import React from 'react';
import {Table, Spin, Card, Button, Row, Col, Form} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, FORM_ROW_OPTIONS, DATETIME_FORMAT} from '../constants';
import {approvePassData, approveBackData, getDetail} from './api';
import TextInput from 'Shared/components/TextInput';
import {injectIntl} from './intl';
import {conventEnumValueToString, formatDateTime} from '../utils';
import {caseType, consultType, exceptionInfoTransferApproveResult} from '../Enum';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import styles from './style.css';
import Return from '../common/Return';
import {newOrApproveOrderValidator} from './validator';
const {Description} = DescriptionList;
const FormItem = Form.Item;

class ApprovePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        data: {},
        details: [],
        approveDetails: []
    }
    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                            details: res.data.details,
                            approveDetails: res.data.approveDetails,
                        });
                    else
                        this.setState({loading: false});
                });
        }
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    // eslint-disable-next-line react/sort-comp
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onApprovePass = () => {
        const data = this.state.data;
        const isValid = newOrApproveOrderValidator(data);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            approveComment: data.approveComment,
            approveTime: data.approveTime,
            rowVersion: data.rowVersion,
        };
        this.setState({loading: true});
        approvePassData(this.props.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onApproveBack = () => {
        const data = this.state.data;
        const isValid = newOrApproveOrderValidator(data);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            approveComment: data.approveComment,
            approveTime: data.approveTime,
            rowVersion: data.rowVersion,
        };
        this.setState({loading: true});
        approveBackData(this.props.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, approveDetails, isValidate, loading} = this.state;
        const {brands} = this.props.initEnumData;
        if(brands.length === 1 && !this.props.id) {
            data.brandId = brands[0].value;
            data.brandName = brands[0].text;
        }
        const approveColumns = [{
            title: formatMessage({
                id: 'approvePanel.column.approverName',
                defaultMessage: '审核人姓名'
            }),
            dataIndex: 'approverName',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.approveTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'approveTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.approveComment',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'approveComment',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.approvedResult',
                defaultMessage: '审核结果'
            }),
            dataIndex: 'approvedResult',
            render: text => conventEnumValueToString(exceptionInfoTransferApproveResult, text)
        }];
        const columns = [{
            title: formatMessage({
                id: 'approvePanel.column.productCategoryCode',
                defaultMessage: '车型编号'
            }),
            dataIndex: 'productCategoryCode',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.productCategoryName',
                defaultMessage: '车型名称'
            }),
            dataIndex: 'productCategoryName',
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'approvePanel.column.common',
                        defaultMessage: '技术案例/通报管理'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.code',
                                        defaultMessage: '编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {this.props.id
                                            ? data.code : <span className="value-font">{formatMessage({
                                                id: 'approvePanel.value.defalut',
                                                defaultMessage: '尚未生成'
                                            })}</span>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item}>
                                        ({data.brandCode}){data.brandName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.caseType',
                                        defaultMessage: '案例类型'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(caseType, data.caseType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.consultType',
                                        defaultMessage: '咨询类型'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(consultType, data.consultType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.faultCode',
                                        defaultMessage: '故障编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.faultCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.caseTitle',
                                        defaultMessage: '案例标题'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.caseTitle}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.sultArea',
                                        defaultMessage: '适用区域'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.sultArea}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.caseDescription',
                                        defaultMessage: '案例描述'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.caseDescription}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.caseAnalysis',
                                        defaultMessage: '案例分析'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.caseAnalysis}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.solution',
                                        defaultMessage: '解决方案'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.solution}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {data.remark}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.approveComment',
                                        defaultMessage: '审核意见'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.approveComment ? 'error' : null} required>
                                        <TextInput
                                            name="approveComment"
                                            value={data.approveComment}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.approveTime',
                                        defaultMessage: '审核时间'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.approveTime ? 'error' : null} required>
                                        {formatDateTime(data.approveTime, DATETIME_FORMAT)}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'approvePanel.operation.detail',
                            defaultMessage: '车型清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="productCategoryId"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card>
                        <DescriptionList title={formatMessage({
                            id: 'approvePanel.table.approveDetails',
                            defaultMessage: '历史审核结果'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={approveColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={approveDetails}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    {data.attachments && data.attachments.length >= 0
                        ? <Card><DescriptionList size="large" title={formatMessage({
                            id: 'approvePanel.card.attachment',
                            defaultMessage: '附件'
                        })}>
                            {data.attachments.map(item => (<Description key={item.id}>
                                <a onClick={this.onClickDownload} key="delete" data-id={item.filePath} data-applyid={item.fileName}>
                                    {item.fileName}</a></Description>))}
                        </DescriptionList></Card>
                        : <Card><DescriptionList size="large" title={formatMessage({
                            id: 'approvePanel.content.noAttachment',
                            defaultMessage: '暂无附件'
                        })}>
                        </DescriptionList></Card>}
                    <Card className={styles.optionBtn}>
                        <Button
                            onClick={this.onApproveBack}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.operation.onApproveBack',
                                defaultMessage: '审核驳回'
                            })}
                        </Button>
                        <Button
                            type="primary"
                            onClick={this.onApprovePass}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.operation.onApprovePass',
                                defaultMessage: '审核通过'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

ApprovePanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ApprovePanel));
